import json

from django.http import HttpResponse
from django.shortcuts import render, redirect
from rest_framework.generics import *
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from sdsm.serializers import *
from .models import  BaseSensitiveInfo,Metadata
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.pagination import *
from rest_framework.mixins import ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin
from rest_framework.pagination import *
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

# Create your views here.

# 自定义分页器
# class MyPageNumber(PageNumberPagination):
#     page_size = 100
#     page_size_query_param = 'size'
#     page_query_param = 'page'
#     max_page_size = None

class SensitiveDataViewSet(ModelViewSet):
    queryset = BaseSensitiveInfo.objects.all()
    serializer_class = SensitiveDataSerializer
    permission_classes = [permissions.IsAuthenticated]


# CBV: class base APIView
# class MetadataAPIView(APIView):
#     def get(self,request):
#         queryset = Metadata.objects.all().filter(classify='手机号')
#         serializer_class = MetadataSerializer(queryset,many=True)
#         pagination_class = MyPageNumber
#         return render(request,'metadata.html',{'metadataapi':serializer_class.data})


# CBV: GernericAPIView 5个实现
# class MetadataView(GenericAPIView,ListModelMixin,CreateModelMixin):
#     queryset = Metadata.objects.all()
#     serializer_class = MetadataSerializer
#     def get(self,request):
#         return self.list(request)
#     def post(self,request):
#         return self.create(request)
#
# class MetadataViewDetail(GenericAPIView,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin):
#     queryset = Metadata.objects
#     serializer_class = MetadataSerializer
#     def get(self,request,pk):
#         return self.retrieve(request,pk)
#     def put(self,request,pk):
#         return self.update(request,pk)
#     def delete(self,request,pk):
#         return self.delete(request,pk)
#

from .tokenauth import *

class MetadataView(ListCreateAPIView):
    authentication_classes = [TokenAuth, ]
    # authentication_classes = [JSONWebTokenAuthentication, ] # 调用drf内置认证
    # 数据脱敏函数
    def data_mask(data):
        for i in data:
            if i['classify'] == '手机号':
                phone = i['simpling01']
                phone = phone.replace(phone[3:7], '****')
                i['simpling01'] = phone
        return data

    def get(self,request):
        status = request.COOKIES.get('JWT_TOKEN')
        if not status:
            return redirect('/login/')
        queryset = Metadata.objects.filter(classify='手机号')[:20]
        serializer_class = MetadataSerializer(queryset,many=True)
        # pagination_class = PageNumberPagination
        data = serializer_class.data
        # print(f'data:{data}')
        # for i in data:
        mask_data = MetadataView.data_mask(data)
        return render(request,'metadata.html',{'metadataapi':mask_data})


class MetadataViewDetail(RetrieveUpdateDestroyAPIView):
    authentication_classes = [TokenAuth, ]
    # authentication_classes = [JSONWebTokenAuthentication, ] # 调用drf内置认证
    queryset = Metadata.objects.all()
    serializer_class = MetadataSerializer
    pagination_class = PageNumberPagination


# api jwt authentication
from django.contrib.auth import authenticate
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER


def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    username = request.POST.get('username')
    password = request.POST.get('password')

    def getjwttoken():
        user = authenticate(username=username, password=password)
        if user:
            if not user.is_active:
                msg = 'User account is disabled.'
                raise serializers.ValidationError(msg)
            payload = jwt_payload_handler(user)
            return {
                'token': jwt_encode_handler(payload),
                'user': user
            }
    user = authenticate(username=username,password=password)
    if not user:
        print('用户名或密码错误，请重新输入...')
        return redirect("/login/")
    else:
        rep = redirect("/metadata/")
        rep.set_cookie("JWT_TOKEN",getjwttoken().get('token'))
        return rep


def logout(request):
    rep = redirect('/login/')
    if request.COOKIES.get('JWT_TOKEN'):
        rep.delete_cookie('JWT_TOKEN')
        return rep
    else:
        return rep
